package com.wosai.teach.activity;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.wosai.teach.R;
import com.wosai.teach.cst.C;
import com.wosai.teach.dialog.NewProgressDialog;
import com.wosai.teach.dto.JsonResult;
import com.wosai.teach.entity.AppUseInfo;
import com.wosai.teach.entity.User;
import com.wosai.teach.pojo.PasswordDTO;
import com.wosai.teach.utils.AppUtil;
import com.wosai.teach.utils.OtherUtils;

/**
 * @author qiumy@wosaitech.com 2015-3-28 上午11:22:19
 * 
 *         登录界面
 * 
 */
@ContentView(R.layout.activity_modify)
public class ModifyActivity extends AppActivity {

	private NewProgressDialog progressdialog;

	@ViewInject(R.id.modify_orig_passwd)
	private EditText origPasswd;

	@ViewInject(R.id.modify_new_passwd)
	private EditText newPasswd;

	@ViewInject(R.id.modify_two_passwd)
	private EditText twoPasswd;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// MobclickAgent.onEvent(this, "login");
		super.onCreate(savedInstanceState);
		enableBack(true);
		setmPageName("更改密码");
		setTopTitle("更改密码");
	}

	@OnClick(value = { R.id.modify_sure })
	public void checkModify(View v) {
		if (!checkNetWorkStatus(getApplicationContext())) {
			toastShow("网络忘记连接啦！");
			return;
		}
		String origStr = origPasswd.getText().toString();
		String newStr = newPasswd.getText().toString();
		String twoStr = twoPasswd.getText().toString();
		if (TextUtils.isEmpty(origStr.trim())) {
			toastShow("请输入原密码");
			return;
		}
		if (TextUtils.isEmpty(newStr.trim())) {
			toastShow("请输入新密码");
			return;
		}
		if (TextUtils.isEmpty(twoStr.trim())) {
			toastShow("请输入密码确认");
			return;
		}
		if (!isPasswordValid(newStr)) {
			toastShow("密码由6-16位数字、字母组成");
			return;
		}
		if (!newStr.equals(twoStr)) {
			toastShow("新密码和密码确认不一致");
			return;
		}
		if(origStr.equals(newStr)||origStr.equals(twoStr)){
			toastShow("新密码和旧密码有区别么0.0，重新输入吧，亲=。=");
			return;
		}
		updatePasswd(origStr, newStr);
	}

	/**
	 * 修改密码
	 */
	public void updatePasswd(String origPasswd, String newPasswd) {
		progressdialog = NewProgressDialog
				.showProgress(this, "努力加载中...", false);
		HttpUtils http = new HttpUtils();
		String url = C.HTTP_USER_PASSWD_MODIFY;
		RequestParams params = new RequestParams();
		User user = db.findFirst(User.class);
		url = url.replace("{userId}", user.getUserId() + "");
		PasswordDTO dto = new PasswordDTO();
		dto.setUserId(user.getUserId());
		dto.setLoginName(user.getLoginName());
		dto.setNewPwd(newPasswd);
		dto.setOldPwd(origPasswd);
		String jsonStr = JSON.toJSONString(dto);
		params.addBodyParameter("pwdDTO", jsonStr);
		http.send(HttpMethod.POST, url, params, new RequestCallBack<String>() {

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				if (OtherUtils.CheckNull(responseInfo.result)) {
					return;
				}
				JsonResult jr = JSON.parseObject(responseInfo.result,
						JsonResult.class);
				if (jr.getResult() == 0) {
					User user = JSON.parseObject(jr.getObject().toString(),
							User.class);
					if (user == null) {
						return;
					}
					db.deleteAll(Selector.from(User.class).where("userId", "=",
							user.getUserId()));
					user.setPassword("");
					db.save(user);
					result(true);
					toastShow(jr.getMessage());
					
					AppUseInfo aui = db.getFirst(AppUseInfo.class);
					aui.setLogin(false);
					db.saveOrUpdate(aui);
					
					Intent it = new Intent(ModifyActivity.this,LoginActivity.class);
					startActivity(it);
					finish();
					
				} else {
					result(false);
//					toastShow(jr.getMessage());
					toastShow("原密码输入有误，请重新输入!");
				}
			}

			@Override
			public void onFailure(HttpException error, String msg) {
				toastShow("修改失败");
				result(false);
			}

		});
	}

	/**
	 * 接口修改成功
	 */
	private void result(boolean result) {
		if (result) {
			origPasswd.setText("");
			newPasswd.setText("");
			twoPasswd.setText("");
		}
		if (progressdialog != null) {
			progressdialog.dismiss();
		}
	}

	public static boolean checkNetWorkStatus(Context context) {
		boolean result;
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netinfo = cm.getActiveNetworkInfo();
		if (netinfo != null && netinfo.isConnected()) {
			result = true;
		} else {
			result = false;
		}
		return result;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN) {
			AppUtil.AppOut(keyCode, event, this);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 验证密码输入格式 [0-9A-Za-z]*
	 * 
	 * @param string
	 * @return matcher.matches()
	 */
	public static boolean isPasswordValid(String string) {

		String expression = "[0-9A-Za-z]{6,16}";
		CharSequence inputStr = string;

		Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(inputStr);
		return matcher.matches();
	}

	/**
	 * 验证账号输入格式 [A-Za-z0-9_]+
	 * 
	 * @param string
	 * @return matcher.matches()
	 */
	public static boolean isLoginNameValid(String string) {

		String expression = "[A-Za-z0-9_]+";
		CharSequence inputStr = string;

		Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(inputStr);
		return matcher.matches();
	}
}
